package com.alphasystem.commerce.common.model.translation;

import static javax.persistence.CascadeType.ALL;
import static javax.persistence.FetchType.EAGER;

import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;

import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.MapKey;
import javax.persistence.MappedSuperclass;
import javax.persistence.OneToMany;
import javax.persistence.Transient;

import com.alphasystem.commerce.common.model.AbstractEntity;

/**
 * @author Syed Farhan Ali
 * 
 */
@MappedSuperclass
public abstract class TranslationInfoSupport extends AbstractEntity {

	private static final long serialVersionUID = -6370459823184884438L;

	protected transient Locale currentLocale;

	protected Map<String, TranslationInfo> translations;

	public TranslationInfoSupport() {
		this(TEMP_ID);
	}

	public TranslationInfoSupport(String id) {
		super(id);
		translations = new LinkedHashMap<String, TranslationInfo>();
		currentLocale = Locale.getDefault();
	}

	@Transient
	public TranslationInfo getCurrent() {
		return (translations != null && !translations.isEmpty()) ? translations
				.get(currentLocale.getLanguage() + "_"
						+ currentLocale.getCountry()) : null;
	}

	public TranslationInfo getTranslationInfo(String key){
		return translations.get(key);
	}

	@OneToMany(fetch = EAGER, cascade = ALL)
	@MapKey(name = "translationKey")
	@JoinTable(name = "ASC_ENT_TRANSLATION_RLTN", joinColumns = { @JoinColumn(name = "entity_id") }, inverseJoinColumns = { @JoinColumn(name = "trans_id") })
	public Map<String, TranslationInfo> getTranslations() {
		return translations;
	}
	
	public TranslationInfo putTranslationInfo(TranslationInfo value) {
		return translations.put(value.getTranslationKey(), value);
	}

	public void setTranslations(Map<String, TranslationInfo> translationMap) {
		this.translations = translationMap;
	}

}
